package com.gy.algorithm.carl.linklistexa;

import java.util.List;

/**
 * @BelongsProject: javabase
 * @BelongsPackage: com.gy.algorithm.carl
 * @Author: gy
 * @Date: 2024/10/22 11:30
 * @Description:
 */
public class DetectCycle142 {

    // write
    public static ListNode detectCycle(ListNode head) {
        // 快慢指针 找相遇点 -> 找环
        ListNode fast = head;
        ListNode slow = head;

        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                // 开始找入口
                ListNode start = head;
                ListNode cicle = fast;
                while(start != cicle){
                    start = start.next;
                    cicle = cicle.next;
                }
                return start;
            }
        }

        return null;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
